package springboot.demo.shiro.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import springboot.demo.shiro.entity.po.User;
import springboot.demo.shiro.service.IUserService;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>Project: springboot-demo </p>
 * 
 * <p>Function:  </p>
 * 
 * <p>Description:  </p>
 * 
 * @author weiqiang.li
 * 
 * @date 2018/11/24
 * 
 * @version 1.0
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    /**
     * 获取身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String userName = usernamePasswordToken.getUsername();
        User user = userService.getOne(new QueryWrapper<User>().eq("name", userName));
        String password = new String(usernamePasswordToken.getPassword());
        if (null == user) {
            throw new UnknownAccountException("用户不存在");
        }
        if (!user.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }
        return new SimpleAuthenticationInfo(userName, password, "cutomRealm");
    }

    /**
     * 获取授权信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // get roles
        Set<String> roles = new HashSet<>();
        authorizationInfo.setRoles(roles);
        // get permissions
        Set<String> permissions = new HashSet<>();
        permissions.add("/user/getList");
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }
}
